package com.example.stream;

import java.util.*;
import java.util.stream.Collectors;

public class MainTest {

    public static void main(String[] args) {
        //Map集合 key为班级ID  List是班级里面的学生
        Map<Long, List<Student>> data = getData();
        System.out.println("map集合的原数据：" + data);
        //1.获取所有班级的学生姓名
        List<String> studentsName = data.values().stream().
                flatMap(studentList -> studentList.stream()).
                map(student -> student.getName()).
                collect(Collectors.toList());
        System.out.println("学生姓名："+studentsName);


        //2.获取所有班级学生id并排序
        List<Long> studentIds = data.values().stream().
                flatMap(Collection::stream).
                map(Student::getId).
                sorted().
                collect(Collectors.toList());
        System.out.println("学生ID排序：" + studentIds);

        //3.所有学生id之和
        Optional<Long> reduce = data.values().stream()
                .flatMap(Collection::stream)
                .map(Student::getId)
                .reduce(Long::sum);
        System.out.println("学生ID之和："+reduce);

    }


    public static Map<Long, List<Student>> getData(){
        Map<Long, List<Student>> data = new HashMap<Long, List<Student>>();
        Student s1 = Student.builder().id(1L).name("张三").build();
        Student s2 = Student.builder().id(2L).name("李四").build();
        Student s3 = Student.builder().id(3L).name("王五").build();
        Student s4 = Student.builder().id(4L).name("赵六").build();
        //1班学生集合
        List<Student> list1 = new ArrayList<Student>();
        list1.add(s1);
        list1.add(s2);
        //2班学生集合
        List<Student> list2 = new ArrayList<Student>();
        list2.add(s3);
        list2.add(s4);
        data.put(1L, list1);
        data.put(2L, list2);
        return data;
    }

}
